<template>
  <div>

    <el-form ref="form"
             :model="article"
             label-width="80px"
             size="mini">

      <el-form-item label="标题">
        <el-input v-model="article.title">
        </el-input>
      </el-form-item>

      <el-form-item label="分类"
                    :inline="true">
        <el-cascader v-model="topicArry"
                     :options="topics"
                     :props="{
              expandTrigger: 'hover',
              value: 'topicId',
              label: 'topicName',
              emitPath: false,
            }"
                     @change="selectTopic"></el-cascader>
        <el-button @click="loadTopics">reload</el-button>
        <el-switch v-model="auto_save"
                   active-text="开启自动保存"
                   inactive-text="关闭自动保存"></el-switch>
        <el-switch v-model="isMarkdown"
                   active-text="markdown编辑器"
                   inactive-text="富文本编辑器"
                   @click="setData"
                   ></el-switch>
      </el-form-item>
      <el-form-item label="内容">
        <markdown :article="article.markdown"
                  :callback="callback"
                  v-show="isMarkdown"> </markdown>
        <div id="editor"
             v-show="!isMarkdown"></div>
        <div id="catalogBox"
             style="display: none" />
      </el-form-item>

      <el-form-item label="开启封面">
        <el-switch v-model="cover"></el-switch>
      </el-form-item>
      <el-form-item label="封面"
                    v-if="cover">
        <img v-if="article.cover"
             :src="article.cover"
             class="avatar"
             style="float: left" />
        <!-- <i v-else class="el-icon-plus avatar-uploader-icon"></i> -->
        <el-upload class="upload-demo"
                   action
                   drag
                   :before-upload="beforeAvatarUpload"
                   :show-file-list="false"
                   :http-request="changeUpload"
                   style="float: left">
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">点击上传</div>
        </el-upload>
        <!-- vueCropper 剪裁图片实现-->
        <el-dialog title="图片剪裁"
                   :visible.sync="dialogVisible"
                   append-to-body>
          <div class="cropper-content">
            <div class="cropper"
                 style="text-align: center">
              <vueCropper ref="cropper"
                          :img="option.img"
                          :outputSize="option.size"
                          :outputType="option.outputType"
                          :info="true"
                          :full="option.full"
                          :canMove="option.canMove"
                          :canMoveBox="option.canMoveBox"
                          :original="option.original"
                          :autoCrop="option.autoCrop"
                          :fixed="option.fixed"
                          :fixedNumber="option.fixedNumber"
                          :centerBox="option.centerBox"
                          :infoTrue="option.infoTrue"
                          :fixedBox="option.fixedBox"></vueCropper>
            </div>
          </div>
          <div slot="footer"
               class="dialog-footer">
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button type="primary"
                       @click="finish"
                       :loading="loading">确认</el-button>
          </div>
        </el-dialog>
      </el-form-item>

      <el-form-item>
        <el-button type="primary"
                   @click="onSubmit(false)">保存</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import E from 'wangeditor'
import hljs from 'highlight.js'
import { addArticle, getArticle, updArticle } from '@/api/apis'
import { qryTopics } from '@/api/topicApis'
import { uploadFileTo7n } from '@/api/fileupload'
import { VueCropper } from 'vue-cropper'
import { editorConfig, vueCropperConfig } from '../config/edit.config.js'
import { mapGetters } from 'vuex'
import markdown from '@/components/editor/markdown'
import TurndownService  from 'turndown'

var turndownService = new TurndownService()
export default {
  name: 'Edit',
  data() {
    return {
      editor: null,
      value: '这里放markdown内容',
      hljsCss: 'agate',
      // 自定义
      imageUploader: {
        custom: true,
        fileType: 'file',
        fileNameType: '',
        imagePrefix: 'http://47.100.125.98', // 图片上传成功后，预览地址前缀
      },
      topicArry: [],
      article: {
        title: '未命名', // 文章标题
        topicId: '', // 分类Id
        topicName: '', // 分类名
        schedTime: '', // 定时发布时间
        cover: '', // 封面图片
        summary: '', // 文章摘要
        sched: 0, // 定时发布
        content: '', // 文章内容
        userId: 1008611, // 作者Id
        copy: 0,
        copyId: '',
        dir: '',
        markdown: ''
      },
      articleContent: '',
      articleMarkdown:'',
      topics: [
        {
          topicName: '12',
          topicId: 123,
        },
      ],
      dialogVisible: false,
      // 裁剪组件的基础配置option
      option: vueCropperConfig,
      picsList: [], // 页面显示的数组
      // 防止重复提交
      loading: false,
      timer: null,
      cover: false,
      loop: true,
      auto_save: false,
      isMarkdown: true
    }
  },
  computed: {
    // 使用对象展开运算符将 getter 混入 computed 对象中
    ...mapGetters([
      'articleId',
      'groupId',
      // ...
    ]),
  },
  components: {
    VueCropper,
    markdown
  },
  mounted() {
    this.editor = new E('#editor')
    editorConfig(this.editor, this.edit, uploadFileTo7n)

    // 编辑器内容回调
    this.editor.config.onchange = (html) => {
      this.articleContent = html
    }

    // 大纲回调
    this.editor.config.onCatalogChange = (arr) => {
      const box = document.getElementById('catalogBox')
      box.innerHTML = ''
      arr.forEach((item, index) => {
        const p = document.createElement(arr[index].tag)
        const a = document.createElement('a')
        a.href = '#' + item.id
        a.title = item.text
        a.innerText = item.text
        p.appendChild(a)
        box.appendChild(p)
      })
      this.article.dir = box.innerHTML
    }

    this.editor.highlight = hljs
    this.editor.config.height = 700
    this.editor.create()

    this.loadTopics()
    this.loadArticle()

    this.timer = setInterval(() => {
      window.console.log('auto submit')
      if (this.auto_save && !this.isMarkdown && this.loop) {
        this.loop = false
        this.onSubmit(true)
      }
    }, 2000)
  },
  beforeDestroy() {
    window.console.log('close timer')
    clearInterval(this.timer)
  },
  watch: {
    content: function (val) {
      this.editor.txt.html(val)
    },
  },
  methods: {
    callback({ mkd, html }) {
      this.articleMarkdown = mkd
      this.editor.txt.html(html)
      this.articleContent = html
      this.onSubmit(true)
    },
    setData() {
      this.editor.txt.html(this.articleContent)
    },
    loadTopics() {
      qryTopics().then(({ data }) => {
        this.topics = data
        data.forEach((e) => {
          if (e.topicId == this.groupId) {
            this.topicArry = [e.topicId]
            return
          }
          if (e.children) {
            e.children.forEach((c) => {
              if (c.topicId == this.groupId) {
                this.topicArry = [e.topicId, c.topicId]
                this.article.topicId = this.groupId
                this.article.topicName = c.topicName
                return
              }
            })
          }
        })
      })
    },
    loadArticle() {
      const atcId = this.articleId
      if (atcId) {
        getArticle({ atcId: atcId, flag: 2 }).then((res) => {
          this.article = res.data
          this.articleContent = res.data.content
          var markdown = turndownService.turndown(this.articleContent)
          this.article.markdown = markdown
          this.topicArry = []
          this.topicArry.push(
            this.article.tbTopic.parentId,
            this.article.topicId
          )
        })
      }
    },
    onSubmit(flag) {
      this.article.content = this.articleContent
      this.article.markdown = this.articleMarkdown
      if (this.articleId) {
        updArticle(this.article).then(() => {
          this.loop = true
          if (!flag) this.$store.commit('blog/setModel', 'list')
        }).catch(() => {
          this.loop = true
        })
      } else if (this.article.topicId) {
        addArticle(this.article).then(({ data }) => {
          this.loop = true
          this.$store.commit('blog/setArticleId', data)
          this.article.atcId = data
          if (!flag) {
            this.$store.commit('blog/setModel', 'list')
          }
        }).catch(() => {
          this.loop = true
        })
      } else {
        this.loop = true
      }
    },
    beforeAvatarUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 10
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 10MB!')
      }
      return isLt2M
    },
    changeUpload(option) {
      const file = option.file
      const reader = new FileReader()
      if (file) {
        reader.readAsDataURL(file)
      }
      reader.onload = () => {
        const src = reader.result
        this.option.img = src
        this.dialogVisible = true
      }
    },
    // 点击裁剪，这一步是可以拿到处理后的地址
    finish() {
      this.$refs.cropper.getCropBlob((data) => {
        this.loading = true
        uploadFileTo7n(data, this.uploadHandler)
      })
    },
    uploadHandler(path) {
      this.article.cover = path
      this.loading = false
      this.dialogVisible = false
    },
    selectTopic(topicId) {
      this.article.topicId = topicId
    },
  },
}
</script>

<style scoped>
#content {
  background-color: white;
  /* padding: 30px 0; */
}
#statement {
  border-left: 3px solid #f56c6c;
  padding: 20px;
  background-color: #ebeef5;
}
.el-header {
  background-color: #b3c0d1;
  color: #333;
  line-height: 60px;
}

.el-aside {
  color: #333;
}

.w-e-text-container {
  /* height: 1000px !important; */
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 200px;
  line-height: 200px;
  text-align: center;
}
.avatar {
  width: 249px;
  height: 178px;
  display: block;
  margin-right: 10px;
  border-radius: 5px;
}
.cropper {
  width: auto;
  height: 300px;
}

.preview {
  color: #999;
}
.w-e-toolbar .w-e-menu:hover {
  z-index: 10002 !important;
}
.w-e-menu a {
  text-decoration: none;
}
.fullscreen-editor {
  position: fixed;
  width: 100vw;
  height: 100vh;
  text-align: left;
  min-height: 550px;
  z-index: 10003;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  background: white;
}

.fullStyle,
.le-editor-container .fullStyle {
  z-index: 10000;
}

/* .fullscreen-editor > .w-e-text-container {
    height: 95% !important;
  } */
</style>
